/*
 Copyright (c) 2012 Roman Truba

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial
 portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
 THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.fcwy.puzzle.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.fcwy.puzzle.utils.HFile;
import com.fcwy.puzzle.utils.HImage;
import com.fcwy.puzzle.utils.HLog;
import com.fcwy.puzzle.utils.MD5;
import com.fcwy.puzzle.utils.PathUtil;

public class UrlTouchImageView extends RelativeLayout {
	private final String TAG = "UrlTouchImageView";
	protected ProgressBar mProgressBar;
	protected TouchImageView mImageView;
	protected Context mContext;

	public UrlTouchImageView(Context ctx) {
		super(ctx);
		mContext = ctx;
		init();

	}

	public UrlTouchImageView(Context ctx, AttributeSet attrs) {
		super(ctx, attrs);
		mContext = ctx;
		init();
	}

	public TouchImageView getImageView() {
		return mImageView;
	}

	@SuppressWarnings("deprecation")
	protected void init() {
		mImageView = new TouchImageView(mContext);
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		mImageView.setLayoutParams(params);
		this.addView(mImageView);
		mImageView.setVisibility(GONE);
		mProgressBar = new ProgressBar(mContext, null,android.R.attr.progressBarStyle);
		params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		params.addRule(RelativeLayout.CENTER_VERTICAL);
		params.setMargins(30, 0, 30, 0);
		mProgressBar.setLayoutParams(params);
		mProgressBar.setIndeterminate(true);
		/*mImageView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					System.out.println("OnClickListener");
					GalleryUrlActivity activity = (GalleryUrlActivity) mContext;
					activity.finish();
				}
			});
		mImageView.setOnLongClickListener(new View.OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {
					System.out.println("OnLongClickListener");
					return false;
				}
			});*/
		this.addView(mProgressBar);
	}

	public void setUrl(String imageUrl) {
		HLog.i(TAG, "url:" + imageUrl);
		new ImageLoadTask().execute(imageUrl);
	}
	public void setImageView(Bitmap bitmap) {
		mImageView.setImageBitmap(bitmap);
		mImageView.setVisibility(VISIBLE);
		mProgressBar.setVisibility(GONE);
	}
	// No caching load
	public class ImageLoadTask extends AsyncTask<String, Integer, Bitmap> {
		@Override
		protected Bitmap doInBackground(String... strings) {
			String url = strings[0];
			HLog.i(TAG, "load image,url is :" + url);
			Bitmap bitmap = null;
			//String point=url.substring(url.length()-4, url.length()-3);
			if (url != null && url.length() > 4) {
				String cacheFilePath = PathUtil.CACHE_IMG + MD5.md5(url);
				if(url.startsWith("http")){
					HLog.i(TAG, "load image:" + url);
					File file = new File(cacheFilePath);
					if (file.exists()) {
						HLog.i(TAG, "The cache file exists");
						try {
							FileInputStream fs = new FileInputStream(file);
							bitmap = BitmapFactory.decodeStream(fs);
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						}
					} else {
						//图片本地不存在，下载图片
						try {
							HFile.createDipPath(cacheFilePath);
							URL urlNet = new URL(url);
							URLConnection conn = urlNet.openConnection();
							InputStream inStream = conn.getInputStream();
							FileOutputStream fs = new FileOutputStream(cacheFilePath);
							byte[] buffer = new byte[1204];
							int length;
							while ( (length = inStream.read(buffer)) != -1) {
								fs.write(buffer, 0, length);
							}
							fs.close();
							
							//下载完成，对下载的图片进行压缩处理。
							bitmap = HImage.getimage(cacheFilePath);
							String imgType = url.substring(url.lastIndexOf(".")+ 1, url.length());
							if(bitmap != null)
								HImage.saveBitmap(bitmap, cacheFilePath, imgType);
						} catch (MalformedURLException e1) {
							HLog.e(TAG, e1.getMessage());
						} catch (FileNotFoundException e1) {
							HLog.e(TAG, e1.getMessage());
						} catch (IOException e1) {
							HLog.e(TAG, e1.getMessage());
						}catch (OutOfMemoryError e1) {
							HLog.e(TAG, e1.getMessage());
						}
				    }
				}else{
					
					File file = new File(url);
					if (file.exists()) {
						HLog.i(TAG, "The cache file exists2");
						try {
//							FileInputStream fs = new FileInputStream(file);
//							bitmap = BitmapFactory.decodeStream(fs);
							bitmap=HImage.getLocalThumbImg(url,480, 800);
						} catch (Exception e) {
							e.printStackTrace();
						}
					} 
				}
					
				/*	try {
						bitmap = BitmapFactory.decodeStream(new URL(url).openStream());
					} catch (MalformedURLException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					if(bitmap != null){
						bitmap = HImage.comp(bitmap);
						String imgType = url.substring(url.lastIndexOf(".")+ 1, url.length());
						HImage.saveBitmap(bitmap,PathUtil.CACHE_IMG + MD5.md5(url),imgType);
					}*/
				
			}
			if(bitmap != null){
				HLog.i(TAG, "width:" + bitmap.getWidth() + " height:" + bitmap.getHeight());
			}
			return bitmap;
		}

		@Override
		protected void onPostExecute(Bitmap bitmap) {
			mImageView.setImageBitmap(bitmap);
			mImageView.setVisibility(VISIBLE);
			mProgressBar.setVisibility(GONE);
		}
	}
}
